import React, { Component } from "react";
import {
  Row,
  Col,
  Card,
  Input,
  Select,
  Button,
  Table,
  Form,
  message,
  Popconfirm
} from "antd";
const { Option } = Select;
import { PageHeaderWrapper } from "@ant-design/pro-layout";
import { connect } from "dva";
import styles from "./index.less";
import CreateUpdateForm from "./components/CreateUpdateForm";
import { pagination, boolean, dateFormat } from "@/utils/utils";
import { informationPerfect } from "@/utils/enum";
import { debounce } from "debounce";
import router from "umi/router";

@connect(({ companyUserManage }) => ({
  zbCompanyUser: companyUserManage.zbCompanyUser
}))
class User extends Component {
  static defaultProps = {
    zbCompanyUser: {}
  };
  constructor(props) {
    super(props);
    this.searchZbCompanyUser = debounce(this.searchZbCompanyUser, 600);
    this.state = {
      createModalVisible: false,
      updateModalVisible: false,
      updateFormData: {
        userDetailResponse: {},
        zbCompanyResponse: {}
      },
      searchParams: {
        auditing: "",
        search: ""
      },
      setPagination: {
        ...pagination
      }
    };
    this.columns = [
      {
        title: "手机号",
        dataIndex: "userDetailResponse.mobile",
        align: "center"
      },
      {
        title: "企业联系人",
        dataIndex: "userDetailResponse.name",
        align: "center"
      },
      {
        title: "企业邮箱",
        dataIndex: "zbCompanyResponse.emailAddress",
        align: "center"
      },
      {
        title: "公司名称",
        dataIndex: "zbCompanyResponse.name",
        align: "center"
      },
      {
        title: "营业执照",
        dataIndex: "zbCompanyResponse.businessLicenseUrl",
        align: "center",
        render: text =>
          text && (
            <a onClick={() => window.open(text)} target="_blank">
              <img height={40} src={text} alt="营业执照" />
            </a>
          )
      },
      {
        title: "注册时间",
        dataIndex: "userDetailResponse.createTime",
        align: "center",
        sorter: (a, b) =>
          Date.parse(a.userDetailResponse.createTime) -
          Date.parse(b.userDetailResponse.createTime),
        render: text => {
          return dateFormat(text);
        }
      },
      {
        title: "账号管理",
        align: "center",
        render: (text, record) => {
          return (
            <Button
              type="link"
              onClick={() =>
                router.push({
                  pathname: "/userManagement/company/account",
                  state: { companyId: record.zbCompanyResponse.id }
                })
              }
            >
              查看
            </Button>
          );
        }
      },
      {
        title: "操作",
        align: "center",
        render: (text, record, index) => (
          <span className={styles.operation}>
            <a
              onClick={() =>
                router.push({
                  pathname: "/userManagement/company/department",
                  state: { companyId: record.zbCompanyResponse.id }
                })
              }
            >
              部门管理
            </a>
            <a
              onClick={() =>
                router.push({
                  pathname: "/userManagement/company/account",
                  state: { companyId: record.zbCompanyResponse.id }
                })
              }
            >
              账号管理
            </a>
            <a
              onClick={() => {
                this.handleUpdateModalVisible(true, record, index);
              }}
            >
              编辑
            </a>
            <Popconfirm
              title={`确认删除企业用户${record.userDetailResponse.name}”？`}
              onConfirm={async () => {
                await this.handleRemove(record, index);
                // action.reload();
              }}
              // onCancel={this.cancel}
              okText="确定"
              cancelText="取消"
            >
              <a href="#">删除</a>
            </Popconfirm>
          </span>
        )
      }
    ];
  }

  componentDidMount() {
    this.searchZbCompanyUser();
  }

  changeInput = async val => {
    const { searchParams } = this.state;
    await this.setState({
      searchParams: {
        ...searchParams,
        search: val
      }
    });
    this.searchZbCompanyUser();
  };

  onClkAuditing = async val => {
    const { searchParams } = this.state;
    if (searchParams.auditing == val) return;
    await this.setState({
      searchParams: {
        ...searchParams,
        auditing: val
      }
    });
    this.searchZbCompanyUser();
  };

  searchZbCompanyUser = () => {
    const { searchParams, setPagination } = this.state;
    const { dispatch } = this.props;
    const searchRequest = {
      ...searchParams,
      auditing: boolean(searchParams.auditing)
    };
    const pagination = {
      page: setPagination.current,
      size: setPagination.pageSize
    };
    dispatch({
      type: "companyUserManage/searchZbCompanyUser",
      payload: { searchRequest, pagination }
    });
  };

  // 页码切换
  handlePageChange = current => {
    const { setPagination } = this.state;
    this.setState({
      setPagination: {
        ...setPagination,
        current
      }
    });
    this.searchZbCompanyUser();
  };

  // 每页/条 切换
  handleSizeChange = (current, pageSize) => {
    const { setPagination } = this.state;
    this.setState({
      setPagination: {
        ...setPagination,
        current,
        pageSize
      }
    });
    this.searchZbCompanyUser();
  };

  handleCreatModalVisible = flag => {
    this.setState({ createModalVisible: flag });
  };

  handleUpdateModalVisible = (flag, values = {}, index) => {
    this.setState({
      updateModalVisible: flag
    });
    if (Object.keys(values).length == 0) return;
    this.setState({
      zbCompanyResponse: values.zbCompanyResponse,
      userDetailResponse: values.userDetailResponse
    });
  };

  // selectTable = async () => {
  //   console.log('selectTable')
  // }

  handleAdd = async fields => {
    const { dispatch } = this.props;
    const hide = message.loading("正在添加");

    try {
      await dispatch({
        type: "companyUserManage/addZbCompanyUser",
        payload: fields
      });
      hide();
      message.success("添加成功");
      this.handleCreatModalVisible(false);
      this.searchZbCompanyUser();
      return true;
    } catch (error) {
      hide();
      message.error("添加失败请重试！");
      return false;
    }
  };

  handleUpdate = async fields => {
    const hide = message.loading("正在配置");
    console.log(fields, 99)
    await this.props.dispatch({
      type: "companyUserManage/editZbCompanyUser",
      payload: fields
    });
    hide();
    message.success("修改成功");
    this.searchZbCompanyUser();
    this.handleUpdateModalVisible(false);
  };

  handleRemove = async (record, index) => {
    const { dispatch } = this.props;
    const hide = message.loading("正在删除");
    if (!record) return true;
    try {
      await dispatch({
        type: "companyUserManage/deleteZbCompanyUser",
        payload: { zbCompanyUserId: record.zbCompanyResponse.id, index }
      });
      hide();
      message.success("删除成功，即将刷新");
      return true;
    } catch (error) {
      hide();
      message.error("删除失败，请重试");
      return false;
    }
  };

  cancel = e => {
    console.log(e);
    message.error("Click on No");
  };

  render() {
    const {
      createModalVisible,
      updateModalVisible,
      zbCompanyResponse,
      userDetailResponse,
      setPagination,
      searchParams
    } = this.state;
    const { zbCompanyUser } = this.props;
    const pagination = {
      ...setPagination,
      total: zbCompanyUser.totalElements,
      showTotal: count => `总共 ${count} 条`,
      onShowSizeChange: this.handleSizeChange,
      onChange: this.handlePageChange
    };
    return (
      <PageHeaderWrapper className={styles.userContainer}>
        <Card bordered={false} className="marginB24">
          <Row type="flex" justify="space-between">
            <Col>
              <Input
                allowClear
                onChange={e => this.changeInput(e.target.value)}
                value={searchParams.search}
                placeholder="姓名/手机号"
                style={{ width: 250 }}
                className="marginR"
              />
              资料是否完善：
              {
                <Select
                  allowClear
                  value={searchParams.auditing}
                  style={{ width: 250 }}
                  onChange={this.onClkAuditing}
                >
                  {informationPerfect.map(item => (
                    <Option key={item.value} value={item.value}>
                      {item.label}
                    </Option>
                  ))}
                </Select>
              }
            </Col>
            <Col>
              {/* <Button type="primary" icon="search" className="marginR" onClick={this.selectTable} >搜索</Button> */}
              <Button
                type="primary"
                icon="plus"
                onClick={() => this.handleCreatModalVisible(true)}
              >
                新增企业用户
              </Button>
            </Col>
          </Row>
        </Card>

        <div className="wrapperClass">
          <Table
            rowKey={record => record.zbCompanyResponse.id}
            columns={this.columns}
            dataSource={zbCompanyUser.content}
            pagination={pagination}
          />
        </div>

        <CreateUpdateForm
          onSubmit={value => this.handleAdd(value)}
          onCancel={() => this.handleCreatModalVisible(false)}
          modalVisible={createModalVisible}
        />

        <CreateUpdateForm
          onSubmit={value => this.handleUpdate(value)}
          onCancel={() => this.handleUpdateModalVisible(false)}
          modalVisible={updateModalVisible}
          zbCompanyResponse={zbCompanyResponse}
          userDetailResponse={userDetailResponse}
        />
      </PageHeaderWrapper>
    );
  }
}

export default Form.create()(User);
